package com.museum.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.map.MapUtil;
import com.museum.common.dto.PassDto;
import com.museum.common.lang.Const;
import com.museum.common.lang.Result;
import com.museum.entity.AdminUser;
import com.museum.service.IAdminUserService;
import com.museum.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.security.Principal;

/**
 * @author Akihi
 * @create 2022/12/09
 */
@Slf4j
@RestController
public class AuthController {
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private IAdminUserService adminUserService;

    @Autowired
    BCryptPasswordEncoder passwordEncoder;
    /*
    使用hutool工具类生成图片验证码并编码为base64，返回给前端
    * */
    @GetMapping("/captcha")
    public Result captcha(HttpServletRequest request, HttpServletResponse response){
        //定义图形验证码的长、宽、验证码字符数、干扰元素个数
        CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(120, 40, 4, 20);
        //图形验证码写出，可以写出到文件，也可以写出到流
        String key = UUID.randomUUID().toString();
        String code = captcha.getCode();
        log.info("验证码 --- {} - {}", key, code);
        //验证码 --- f7d2b406-ed69-44f0-81c6-87a4b602e871 - 91ai
        //写入流并进行Base64编码
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        captcha.write(outputStream);
        String str = "data:image/jpeg;base64,";
        String base64Img = str + Base64.encode(outputStream.toByteArray());
        //存储到redis中(60s有效期)
        redisUtil.hset(Const.CAPTCHA_KEY, key, code, 60);
        //验证图形验证码的有效性，返回boolean值
        //captcha.verify("1234");
        return Result.success(
                MapUtil.builder()
                        .put("token", key)
                        .put("base64Img", base64Img)
                        .build()
        );
    }
    /*获取当前登录用户详情*/
    @GetMapping("/sys/userInfo")
    public Result userInfo(Principal principal){

        AdminUser adminUser = adminUserService.getByUsername(principal.getName());
        return Result.success(MapUtil.builder()
                .put("id", adminUser.getId())
                .put("username", adminUser.getUsername())
                .map()
        );
    }
    /*更新用户密码*/
    @PostMapping("/sys/user/updatePass")
    public Result updatePass(@Validated @RequestBody PassDto passDto, Principal principal) {

        AdminUser adminUser = adminUserService.getByUsername(principal.getName());

        boolean matches = passwordEncoder.matches(passDto.getCurrentPass(), adminUser.getPassword());
        if (!matches) {
            return Result.fail("旧密码不正确");
        }

        adminUser.setPassword(passwordEncoder.encode(passDto.getPassword()));

        adminUserService.updateById(adminUser);
        return Result.success("更新密码成功");
    }
}
